<?php
namespace Music;

class Kuwo extends MusicBase{
    
    //http://60.29.226.189:9001 测试服务器
    private $api = array(
        'artist_search' => 'http://bd.kuwo.cn/mpage/api/commhzsearch?key={keyword}&pn={page}&rn={page_size}',//搜索歌手列表接口
        'artist_songs'=> 'http://bd.kuwo.cn/mpage/api/artistSongs?artistid={artistid}&sortby=1&pn={page}&rn={page_size}',//歌手单曲列表接口
        'song_experience' => 'http://m.kuwo.cn/?mid=MUSIC_{song_id}&from=meipai',//歌曲试听地址  ，你没看错，就是from，不是其它接口的dbfrom
        'song_info' => 'http://bd.kuwo.cn/mpage/api/getMusicInfo?id={song_id}',//歌曲详细信息接口
        
        //旧接口
        //'song_file' => 'http://bd.kuwo.cn/mpage/service/songUrl?mid={song_id}&format={file_ext}',//歌曲音频资源（下载地址）
        //'song_search' => 'http://bd.kuwo.cn/mpage/api/searchForKS?key={keyword}&pn={page}&rn={page_size}',//6.搜索歌曲接口
        
        //新接口
        'song_search' => 'http://www.kuwo.cn/bd/search/getMusicsByKeyWord?key={keyword}&pn={page}&rn={page_size}',
        'song_file' => 'http://www.kuwo.cn/bd/search/getSongUrlByMid?mid={song_id}&format={file_ext}',
        
    );
    
    private $api_key = 'bdfrom=meipai&c=a8sepeovl0ld'; //这个key设计得也是有点怪，对方怎么说就怎么用吧
    
    
    function getArtistList($keyword , $page, $page_size){
        $params = array(
            'keyword' => $keyword,
            'page' => $this->_fixPageMeipai2Kuwo($page),
            'page_size' => $page_size
        );
        $url = $this->createUrl('artist_search', $params);

        $MtCurl = loadClass('MtCurl');
        $MtCurl->setFatalMailInterval(10);
        $r = $MtCurl->get($url , $timeout=300);
        $r = @json_decode($r,true);
        
        $return_data = array();
        
        if($r['abslist']){
            foreach ($r['abslist'] as $v){
                $data = array(
                    'id' => $v['ARTISTID'],
                    'name' => $v['ARTIST'],
                    'pic' => $v['PICPATH'],
                    'area' => $v['COUNTRY'],
                    'song_num' => $v['SONGNUM'],
                );
                $return_data[] = $data;
            }
        }
        
        return $return_data;
    }
    
    function getSongListTemp($keyword , $page, $page_size){

        /****酷我搜索接口坏了，临时替换策略****/
        $url = 'http://search.kuwo.cn/r.s?SONGNAME="'.urlencode($keyword).'"&ft=music&rformat=json&encoding=utf8&rn='.$page_size.'&pn='.$page;
        $MtCurl = loadClass('MtCurl');
        $MtCurl->setFatalMailInterval(100);
        $r = $MtCurl->get($url , $timeout=5);
        if(preg_match_all("|'SONGNAME':'(.*?)','ARTIST':'(.*?)'.*?'ALBUM':'(.*?)'.*?'FILESIZE':'(\d+)'.*?,'DURATION':'(\d+)'.*?'SCORE':'(\d+)'.*?'MUSICRID':'MUSIC_(\d+)'|", $r, $match)){
            $return_data = array();
            foreach ($match[0] as $k=>$V){
                $return_data[] = array(
                    'id' => $match[7][$k],
                    'score' => $match[6][$k],
                    'duration' => $match[5][$k],
                    'file_size' => $match[4][$k],
                    'album' => $match[3][$k],
                    'artist' => $match[2][$k],
                    'name' => $match[1][$k],
                );
            }
            return $return_data;
        }else{
            return array();
        }
    }

    function getSongList($keyword , $page, $page_size){
        
        return $this->getSongListTemp($keyword , $page, $page_size);
        
        $params = array(
            'keyword' => $keyword,
            'page' => $this->_fixPageMeipai2Kuwo($page),
            'page_size' => $page_size
        );
        $url = $this->createUrl('song_search', $params);

        $MtCurl = loadClass('MtCurl');
        $MtCurl->setFatalMailInterval(100);
        $r = $MtCurl->get($url , $timeout=5);
        $r = @json_decode($r,true);
        
        
        $return_data = array();
        
        if($r['data']){
            foreach ($r['data'] as $v){
                $data = array(
                    'id' => $v['id'],
                    'duration' => $v['duration'],
                    'name' => str_replace('&nbsp;', ' ', $v['songName']),
                    'album' => $v['album'],
                    'artist' => $v['artist'],
                    'file_size' => $v['size'],
                    'wap_url' => $this->_getSongWapUrl($v['id']),
                );
                $return_data[] = $data;
            }
        }
        
        return $return_data;
    }
    
    private function _fixPageMeipai2Kuwo($meipai_page){
        $kuwo_page = $meipai_page-1;//他们的page是从0开始，我们的从1开始
        return $kuwo_page;
    }
    private function _fixPageKuwo2Meipai($kuwo_page){
        $meipai_page = $kuwo_page+1;//他们的page是从0开始，我们的从1开始
        return $meipai_page;
    }
    
    function createUrl($api_type , $params){
        foreach ($params as $_pattern=>$_replace){
            $patterns[] = '{'.$_pattern.'}';
            $replaces[] = urlencode($_replace);
        }
        $url = str_replace($patterns, $replaces, $this->api[$api_type]);
        //QQ记录:luger  18:45:27  所有接口带上参数bdfrom=meipai&c=a8sepeovl0ld
        $url .= '&'.$this->api_key;
        return $url;
    }
    
    function getSongUrl($song_id , $file_ext='mp3'){

        if($file_ext != 'aac'){
            $file_ext = 'mp3';
        }
        
        $params = array(
            'song_id' => $song_id,
            'file_ext' => $file_ext,
        );
        $url = $this->createUrl('song_file', $params);
        
        $MtCurl = loadClass('MtCurl');
        $try_times = 0;
        while ($try_times<=3){
            $try_times++;
            $MtCurl->setFatalMailInterval(100);
            $r = $MtCurl->get($url , $timeout=5);
            $r = @json_decode($r,true);
            
            if($r['data']['url'] == 'res not found'){//这接口查找失败了会返回{"status":"1","data":{"url":"res not found"},"msg":"success"}
                return '';
            }
            
            if($r['data']['url'] && substr($r['data']['url'], 0,4)=='http'){ 
                return  $r['data']['url'];
            }
        }
        
        return '';
    }
    
    function _getSongWapUrl($id){
        //"http://m.kuwo.cn/?mid=MUSIC_6560246&bdfrom=meipai
        $params =array(
            'song_id'=>$id,
        );
        $url = $this->createUrl('song_experience', $params);
        return $url;
    }
    
}